package com.xzq.hm;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;

import java.text.SimpleDateFormat;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 11:47
 * @Version 1.0.0
 **/
public class NettyHttpServer {
    public static void main(String[] args) {
        new NettyHttpServer().lister(9999);
    }

    private void lister(int port) {
        NioEventLoopGroup boos = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            new ServerBootstrap()
                    .group(boos, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HttpServerCodec());
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
                                    System.out.println(msg.getUri());
                                    System.out.println(msg);

                                    //写回响应
                                    DefaultFullHttpResponse response = new DefaultFullHttpResponse(msg.protocolVersion(), HttpResponseStatus.OK);
                                    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, "<h1>hello,world!</h1>".getBytes().length);
                                    response.content().writeBytes("<h1>hello,world!</h1>".getBytes());
                                    System.out.println("<h1>hello,world!</h1>".getBytes().length);
                                    //写回响应
                                    ctx.writeAndFlush(response);
                                }
                            });
                        }
                    })
                    .bind(port).sync()
                    .channel().closeFuture()
                    .sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
            boos.shutdownGracefully();
        }
    }
}
